import { util } from '.'

const historyKey = 'history-list'

function fetchData(url: string) {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error))
  })
}

async function forecast(city: string) {
  const { weatherUrl, weatherKey } = util.Setting.getSetting()

  if (!weatherUrl || !weatherKey) {
    alert('Weather API URL or API key is not set.')
    throw new Error('Weather API URL or API key is not set.')
  }

  const urlQuery = weatherUrl.replace('{key}', weatherKey)
  return await fetchData(`${urlQuery}&q=${city},cn`)
}

// async function getWeather(city: string) {
//   return await fetchData(`/data/2.5/weather?q=${city}`)
// }

function store(data: any): void {
  localStorage.setItem(historyKey, JSON.stringify(data))
}

function getHistoryList(): [] {
  try {
    const historyList = localStorage.getItem(historyKey) || '[]'
    return JSON.parse(historyList)
  } catch (error) {
    return []
  }
}

function clearHistoryList(): void {
  localStorage.removeItem(historyKey)
}

export default {
  forecast,
  store,
  getHistoryList,
  clearHistoryList,
  // getWeather,
}
